<template>
  <Page :title="navTitle">
    <template #navBarCustom>
      <div class="flex items-center navBox">
        <div class="back" @click="back">
          <img class="icon" src="static/icons/back.png" mode="" />
          <span style="color: #fff">{{ navTitle }}</span>
        </div>
        <div class="nav-bar-btns flex" style="margin-left: auto">
          <div class="item flex items-center" @click="showSetting">
            <img class="icon mt-2px mr-4px" src="static/icons/setting.png" mode="" />
            <span class="name text-white">设置</span>
          </div>
        </div>
      </div>
    </template>
    <template #content>
      <div class="w-full h-full px-20px pt-20px box-border flex flex-col">
        <div
          class="container w-full h-full flex-1 flex flex-col bg-white overflow-hidden"
        >
          <div ref="scroll" class="w-full h-full overflow-scroll">
            <!-- 听后选择 -->
            <Choose ref="choose" v-if="questionType === 'choose'" />
            <!-- 听后回答 -->
            <Dialogue ref="dialogue" v-if="questionType === 'dialogue'" />
            <!-- 短文朗读 -->
            <Read ref="read" v-if="questionType === 'read'" />
            <!-- 听后记录 -->
            <Fill ref="fill" v-if="questionType === 'fill'" />
            <!-- 听后转述 -->
            <Picture ref="picture" v-if="questionType === 'picture'" />
            <!-- 听后记录并转述  -->
            <FillPicture ref="fill_picture" v-if="questionType === 'fill_picture'" />
          </div>
        </div>
        <!-- 操作区 -->
        <div class="operate-wrap flex items-center py-30px">
          <img
            class="icon mr-10px"
            :src="isPause ? 'static/icons/play.png' : 'static/icons/playing.png'"
            mode=""
            @click="isPause ? controller.setStatus('normal') : controller.setStatus('pause')"
          />
          <div class="tips text-333">
            <span>{{ operateTips }}</span>
          </div>
        </div>
        <!-- 设置 -->
        <div class="setting-wrap flex flex-col justify-center" v-show="isShowSetting">
          <div class="setting bg-white px-30px py-40px relative flex flex-col">
            <div
              class="controller py-20px relative w-full flex justify-center items-center text-white"
            >
              <img
                class="close absolute"
                src="static/icons/close.png"
                mode=""
                @click="isShowSetting = false"
              />
              <img
                class="prev-stage"
                src="static/icons/prev-stage.png"
                mode=""
                @click="toPrevStage()"
              />
              <img
                class="current-status mx-40px"
                :src="isPause ? 'static/icons/play.png' : 'static/icons/playing.png'"
                mode=""
                @click="isPause ? controller.setStatus('normal') : controller.setStatus('pause')"
              />
              <img
                class="next-stage"
                src="static/icons/next-stage.png"
                mode=""
                @click="toNextStage()"
              />
            </div>
            <div class="main text-333 pt-20px">
              <div class="operate-tips flex justify-center"
                ><span class="text-left">{{ operateTips }}</span></div
              >
              <div class="py-30px flex justify-between items-center">
                <div style="width: 2.03rem; height: 0; border: 0.01rem solid #eeeeee"></div>
                <div style="font-size: 0.18rem">语速调节</div>
                <div style="width: 2.03rem; height: 0; border: 0.01rem solid #eeeeee"></div>
              </div>
              <div class="speed flex justify-between">
                <div
                  class="btn flex-center"
                  :class="controller.speed < 1 ? 'active' : ''"
                  @click="controller.changeSpeed('turnDown')"
                  >放慢</div
                >
                <div
                  class="btn flex-center"
                  :class="controller.speed === 1 ? 'active' : ''"
                  @click="controller.changeSpeed('normal')"
                  >正常</div
                >
                <div
                  class="btn flex-center"
                  :class="controller.speed > 1 ? 'active' : ''"
                  @click="controller.changeSpeed('turnUp')"
                  >加快</div
                >
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </Page>
</template>

<script>
import Page from '@/components/page/newPage'
import { mapState } from 'vuex'
import Controller from './controller'
import Choose from './components/choose'
import Dialogue from './components/dialogue'
import Read from './components/read'
import Fill from './components/fill'
import Picture from './components/picture'
import FillPicture from './components/fill-picture'
import questionJson from './question.json'
import { upExamQuestionAnswerApi } from '@/api/homework'
import { debounce } from '@/utils'

export default {
  components: { Page, Choose, Dialogue, Read, Fill, Picture, FillPicture },
  provide() {
    return {
      globalData: this.$data
    }
  },
  beforeRouteLeave(to, from, next) {
    if (to.name === 'homework_detail_english_index') {
      next()
      return
    }

    if (this.canBack) {
      next()
    } else {
      window.history.pushState(
        null,
        null,
        location.pathname + '#/pages/homework/todo/question/english/index'
      )
      this.$popup.show({
        type: 'confirm',
        success: (popup) => {
          popup.$on('cancel', () => {
            this.$popup.hide('confirm')
          })
          popup.$on('confirm', () => {
            this.$popup.hide('confirm')

            this.canBack = true
            this.$router.back()
          })
          popup.setData({
            title: '确认退出？',
            content: '本次进度将保存',
            cancelText: '取消',
            confirmText: '退出'
          })
        }
      })
    }
  },
  data() {
    return {
      canBack: false,
      // 累计时间
      cumulativeTime: {
        vm: this._self,
        timeout: null,
        // 单位：秒
        value: 0,
        // 累加
        run: function () {
          this.timeout = setTimeout(() => {
            this.value++
            this.run()
          }, 1000)
        },
        reset: function () {
          clearTimeout(this.timeout)
          this.value = 0
        }
      },
      isShowSetting: false,
      repetitiveListening: 1,
      controller: new Controller(),
      toPrevStage: debounce(() => {
        this.controller.toPrevStage()
      }, 300),
      toNextStage: debounce(() => {
        this.controller.toNextStage()
      }, 300)
    }
  },
  computed: {
    ...mapState(['homework']),
    currentHomework() {
      return this.homework.currentHomework
    },
    questionIndex() {
      const { questionIndex } = this.currentHomework
      return questionIndex
    },
    questions() {
      const { questions } = this.currentHomework
      return questions
    },
    currentQuestion() {
      const { questions, questionIndex } = this.currentHomework

      if (!questions || questions.length === 0) return {}

      return questions[questionIndex]
    },
    questionType() {
      const { stem = {} } = this.currentQuestion
      const { structure_type = '' } = stem

      return structure_type.replace('collector.', '')
    },
    navTitle() {
      const { questions, questionIndex } = this.currentHomework
      const order = questionIndex + 1
      const total = questions.length
      const { stem = {} } = this.currentQuestion
      const { structure_type = '' } = stem

      switch (structure_type) {
        case 'collector.choose':
          return `听后选择(${order}/${total})`
        case 'collector.dialogue':
          return `听后回答(${order}/${total})`
        case 'collector.read':
          return `短文朗读(${order}/${total})`
        case 'collector.fill':
          return `听后记录(${order}/${total})`
        case 'collector.picture':
          return `听后转述(${order}/${total})`
        case 'collector.fill_picture':
          return `听后记录并转述(${order}/${total})`
        default:
          return ''
      }
    },
    operateTips() {
      const { operateTips } = this.controller
      return operateTips
    },
    isPause() {
      if (this.controller.getStatus() === 'pause') {
        return true
      } else {
        return false
      }
    }
  },
  watch: {
    questionIndex: {
      handler(newVal, oldVal) {
        if (oldVal === -1 || this.questions.length === 0) return

        const {
          stem: { structure_type: new_structure_type },
          extraInfo: {
            english: { stageIndex = 0 }
          }
        } = this.questions[newVal]
        let old_structure_type = ''
        try {
          old_structure_type = this.questions[oldVal].stem.structure_type
        } catch (error) {}

        this.$nextTick(() => {
          let refComp = this.$refs[new_structure_type.replace('collector.', '')]

          // 题型相同，跳过题型说明
          if (new_structure_type === old_structure_type) {
            refComp.init(1)
          } else {
            refComp.init(stageIndex)
          }
        })
      },
      immediate: true
    },
    currentHomework: {
      handler(newVal, oldVal) {
        const {
          record: { id }
        } = newVal

        this.$storage.homework.putCacheItem({
          id,
          value: newVal
        })
      },
      immediate: false,
      deep: true
    },
    isPause(newVal) {
      let refComp =
        this.$refs.choose ||
        this.$refs.dialogue ||
        this.$refs.read ||
        this.$refs.fill ||
        this.$refs.picture ||
        this.$refs.fill_picture

      if (newVal) {
        refComp.$emit('pause')
      } else {
        refComp.$emit('resume')
      }
    }
  },
  created() {
    //this.init()
    const {
      record: { repetitiveListening }
    } = this.currentHomework

    this.repetitiveListening = repetitiveListening
    this.controller.onStageIndexChange = (currentStageIndex) => {
      try {
        const {
          extraInfo: { english }
        } = this.currentQuestion

        english.stageIndex = currentStageIndex
      } catch (error) {}
    }
    this.controller.onSubmit = this.submit
  },
  mounted() {
    this.cumulativeTime.run()
  },
  beforeDestroy() {
    this.cumulativeTime.reset()
    this.controller.destroy()
  },
  methods: {
    back() {
     this.$router.back()
    },
    init() {
      this.$store.commit('setCurrentHomework', {
        record: {},
        questions: questionJson.data
          .map((q, index) => {
            q['stem'] = JSON.parse(q.stem)
            q['answer'] = JSON.parse(q.answer)
            q['localStudentAnswer'] = {
              examId: '',
              questionId: '',
              studentId: '',
              completeFlag: index === questionJson.data.length - 1 ? 1 : 0,
              studentAnswer: '',
              studentAnswerUrl: '',
              studentDuration: 0
            }
            // 答题状态 0 => 未答题 1 => 已答题
            q['localStudentAnswerStatus'] = 0
            if (q.stem.structure_type != 'collector.fill') {
              return undefined
            }
            return q
          })
          .filter((q) => !!q),
        questionIndex: 0
      })
    },
    showSetting() {
      if (!this.repetitiveListening) {
        this.$message.info('不允许反复听')
        return
      }

      this.isShowSetting = true
    },
    submit() {
      // 不是最后一题，切换下一题
      if (this.questionIndex < this.questions.length - 1) {
        // 更新做题时间
        const { localStudentAnswer } = this.currentQuestion
        localStudentAnswer.studentDuration += this.cumulativeTime.value
        this.cumulativeTime.reset()
        this.cumulativeTime.run()
        this.currentHomework.questionIndex++
        return
      }

      const {
        record: { id },
        questions
      } = this.currentHomework

      const _submit = (questions) => {
        const loading = this.$loading({
          lock: true,
          text: '提交答案...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.5)'
        })
        // 一分钟内上传不成功关闭loading弹窗
        const timer = setTimeout(() => {
          loading.close()
        }, 60000)
        const submitItem = async (questions) => {
          if (questions.length > 0) {
            const question = questions.shift()
            const {
              localStudentAnswer: nextItem,
              stem: { structure_type }
            } = question

            if (
              structure_type === 'collector.choose' ||
              structure_type === 'collector.fill_picture'
            ) {
              // 听后选择/听后记录并转述
              const { questionIds } = question

              Promise.all(
                questionIds.map(async (id, index) => {
                  let formdata = nextItem
                  const copyNextItem = JSON.parse(JSON.stringify(nextItem))
                  copyNextItem.questionId = id
                  try {
                    const studentAnswerItem = copyNextItem.studentAnswer.anSqs[index]
                    copyNextItem.studentAnswer = JSON.stringify({ anSqs: studentAnswerItem })
                  } catch (error) {}
                  if (copyNextItem.completeFlag === 1) {
                    index < questionIds.length - 1 && (copyNextItem.completeFlag = 0)
                  }
                  formdata = copyNextItem
                  return await upExamQuestionAnswerApi(formdata)
                })
              ).then(() => {
                submitItem(questions)
              })
            } else {
              let formdata = nextItem
              const copyNextItem = JSON.parse(JSON.stringify(nextItem))
              copyNextItem.studentAnswer = JSON.stringify(copyNextItem.studentAnswer)
              formdata = copyNextItem
              await upExamQuestionAnswerApi(formdata)
              submitItem(questions)
            }
          } else {
            clearTimeout(timer)
            loading.close()
            this.$message.success('提交成功')
            this.$router.replace('/pages/homework/detail/question/english/index')
            this.$nextTick(() => this.$storage.homework.deleteCacheItem(id))
          }
        }

        submitItem(JSON.parse(JSON.stringify(questions)))
      }

      // 最后一题，提交答案
      // 更新做题时间
      const { localStudentAnswer } = this.currentQuestion
      localStudentAnswer.studentDuration += this.cumulativeTime.value
      this.cumulativeTime.reset()

      _submit(questions)
    }
  }
}
</script>

<style lang="scss" scoped>
.navBox {
  padding: 0 20px;
  box-sizing: border-box;
}
.back {
  height: 100%;
  display: flex;
  align-items: center;
  font-size: 28px;

  .icon {
    width: 17.14px;
    height: 30px;
    margin-right: 11px;
  }
}
.nav-bar-btns {
  .item {
    height: 30px;
    .icon {
      width: 22px;
      height: 22px;
    }

    .name {
      font-size: 22px;
      line-height: 22px;
    }
  }
}

.container {

  /deep/ .type-intro {
    white-space: break-spaces;
    word-break: break-all;
    font-size: 0;

    .type {
      font-size: 0.22rem;
      line-height: 0.22rem;
      font-weight: 500;
    }

    .intro {
      font-size: 0.18rem;
      line-height: 0.28rem;
    }
  }
}

.operate-wrap {
  font-size: 26px;

  .icon {
    width: 70px;
    height: 70px;
  }

  .tips {
  }
}

.setting-wrap {
  width: 100vw;
  height: 100vh;
  background: rgba($color: #000000, $alpha: 0.5);
  position: absolute;
  left: 0;
  top: 0;
  z-index: 1999;

  .setting {
    width: 646px;
    min-height: 241px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    border-radius: 16px;
    border: 1px solid #707070;

    .controller {
      .close {
        width: 16px;
        height: 16px;
        top: -22px;
        right: -14px;
      }

      .prev-stage {
        width: 70px;
        height: 70px;
      }

      .current-status {
        width: 70px;
        height: 70px;
      }

      .next-stage {
        width: 70px;
        height: 70px;
      }
    }

    .main {
      font-size: 20px;
      line-height: 28px;

      .speed {
        font-size: 22px;
        color: #a3a3a3;
        font-weight: 400;

        .btn {
          width: 160px;
          height: 50px;
          border-radius: 25px;
          border: 1px solid #d9d9d9;

          &.active {
            border: 0.01rem solid #51c3ff;
            color: #51c3ff;
          }
        }
      }
    }
  }
}
</style>
